import { useState, useEffect, useMemo, useRef, Fragment } from 'react';
import { Table, Form, Modal } from 'com';
import { Button, Row, Col, Divider, message, Space } from 'antd';
import { confirm, asyncConfirm } from '@/utils/common';
import menuStore from 'store/menu';
import { getAttendanceList } from 'api/dictionary';
import { AddFlow, UpdateFlow, GetList, DeleteFlow } from 'api/teacher_attendance_audit';
import { PlusOutlined, DeleteOutlined, ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';

/**
 * 下标
 */
let idx = 1;

export default () => {
    /**
        * 列表
        */
    const [list, setList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * form表单的引用
     */
    let [forms, setForms] = useState({});
    /**
     * 步骤
     */
    const [steps, setSteps] = useState([]);
    /**
     * 考勤类型
     */
    const [attendances, setAttendances] = useState([]);
    /**
     * 审批对象
     */
    const [flow, setFlow] = useState({});
    /**
     * 考勤类型引用
     */
    const attendanceRef = useRef();
    /**
     * 添加修改MF引用
     */
    const addMF = useRef();
    /**
     * 搜索表单配置项
     */
    const options = useMemo(() => ({
        teacher_id: {
            title: '教师',
            tag: 'ts',
            clear: true
        },
        start_date: {
            title: '开始日期',
            tag: 'date'
        },
        end_date: {
            title: '结束日期',
            tag: 'date'
        },
        status: {
            title: '状态',
            tag: 'select',
            style: { width: 110 },
            values: [{ label: '所有', value: 2 }, { label: '入职', value: 1 }, { label: '离职', value: 0 }]
        },
        search: {
            tag: 'button',
            text: '搜索',
            loading,
            htmlType: 'submit',
            type: 'primary'
        },
        add: {
            tag: 'button',
            text: '添加',
            type: 'primary',
            click: () => {
                addMF.current.show();
            }
        }
    }), [loading]);

    /**
     * 列
     */
    const cols = [
        {
            title: '考勤类型',
            dataIndex: 'type',
            align: 'center'
        },
        {
            title: '审批步数',
            dataIndex: 'step',
            align: 'center',
        },
        {
            title: '审批教师',
            dataIndex: 'count',
            align: 'center',
        },
        {
            title: '操作',
            width: 150,
            align: 'center',
            render: (text, row) => <Space>
                <Button type="link" size="small" onClick={() => update(row)}>修改</Button>
                {menuStore.auth('deleteAttendance') && <Button type="link" size="small" onClick={() => deleteFlow(row)}>删除</Button>}
            </Space>
        }
    ]
    /**
     * 添加修改表单配置项
     */
    const addUpdateOptions = useMemo(() => ({
        teacher_id: {
            title: '审核人',
            tag: 'ts',
            required: true,
            multi: true,
            clear: true
        }
    }), []);
    /**
     * 考勤类型表单配置项
     */
    const attendanceOptions = useMemo(() => ({
        attendance_id: {
            title: '考勤类型',
            required: true,
            tag: "select",
            attrs: { disabled: !!flow.attendance_id },
            values: attendances
        }
    }), [attendances, flow]);

    /**
     * 获取审批列表
     */
    const getList = async () => {
        try {
            setLoading(true);
            const list = await GetList();
            const data = {};
            for (const item of list) {
                (data[item.attendance_id] = data[item.attendance_id] || []).push(item);
            }
            setList(Object.values(data).map(item => ({
                id: item[0].id,
                type: item[0].attendance_name,
                step: Math.max(...item.map(c => c.step)),
                count: item.length,
                data: item
            })));
        } catch (error) { }
        setLoading(false);
    }

    /**
     * 删除审批流
     * @param {*} row 
     */
    const deleteFlow = async row => {
        let res;
        try {
            res = await asyncConfirm(`您确定要删除【${row.type}】审批流吗？`);
            await DeleteFlow(row.data[0].attendance_id);
            getList();
        } catch (error) { }
        res?.close();
    }

    useEffect(() => {
        addForm();
        getList();
        (async () => {
            try {
                const list = await getAttendanceList();
                setAttendances(list.map(c => ({ label: c.name, value: c.id })));
            } catch (error) { }
        })()
    }, []);

    /**
     * 提交
     */
    const ok = async () => {
        const list = [];
        let id = 0;
        try {
            const { attendance_id } = await attendanceRef.current.validateFields();
            id = attendance_id;
            for (const [key, item] of Object.entries(forms)) {
                const { teacher_id } = await item?.validateFields();
                const index = steps.findIndex(c => c.key == key);
                list.push(...teacher_id.map(c => ({ step: index + 1, teacher_id: c })));
            }
        } catch (error) {
            console.log(error);
            return;
        }
        try {
            addMF.current.start();
            await (flow.attendance_id ? UpdateFlow : AddFlow)({ attendance_id: id, steps: list });
            getList();
            addMF.current.hide();
        } catch (error) {
            console.log(error);
        }
        addMF.current.stop();
    }

    /**
     * 添加表单
     */
    const addForm = (teachers) => {
        steps.push({
            key: ++idx, element: <Form ref={(idx => {
                return v => {
                    forms[idx] = v;
                    setForms(forms);
                }
            })(idx)} values={teachers} options={addUpdateOptions} />
        });
        setSteps([...steps]);
    }

    /**
     * 修改
     * @param {*} row 
     */
    const update = ({ data }) => {
        const teachers = {};
        data.forEach(item => {
            (teachers[item.step] = teachers[item.step] || []).push({ id: item.teacher_id, name: item.teacher_name });
        });
        setFlow({ attendance_id: data[0].attendance_id });
        steps.splice(0, steps.length);
        forms = {};
        Object.values(teachers).forEach(item => {
            addForm({ teacher_id: item });
        });
        addMF.current.show();
    }

    return <div>
        <h3>审批流程设置列表</h3>
        <hr />
        <Button type="primary" onClick={() => {
            setFlow({});
            steps.splice(0, steps.length);
            forms = {};
            addForm();
            addMF.current.show();
        }}>添加</Button>
        <p></p>
        {menuStore.auth('teachersStatus') && <Table cols={cols} data={list} loading={loading} />}
        <Modal onOk={ok} title={(flow.attendance_id ? '修改' : '添加') + '考勤审批流'} ref={addMF}>
            <>
                <Form options={attendanceOptions} ref={attendanceRef} values={flow} />
                {
                    steps.map((item, index) => <Fragment key={item.key}>
                        <Divider children={`第${index + 1}步`} />
                        {item.element}
                        <Row justify="end">
                            <Col>
                                <Space size={5}>
                                    <Button onClick={async () => {
                                        if (steps.length === 1) {
                                            return message.warning('审批流至少要有一步，无法删除');
                                        }
                                        try {
                                            await confirm(`您确定要删除第${index + 1}步吗？`);
                                            steps.splice(index, 1);
                                            setSteps([...steps]);
                                            delete forms[item.key];
                                            setForms({ ...forms });
                                        } catch (error) { }
                                    }} type="primary" icon={<DeleteOutlined />} />
                                    {index < steps.length - 1 && <Button onClick={() => {
                                        const obj = steps[index];
                                        steps[index] = steps[index + 1];
                                        steps[index + 1] = obj;
                                        setSteps([...steps]);
                                    }} type="primary" icon={<ArrowDownOutlined />} />}
                                    {index > 0 && <Button onClick={() => {
                                        const obj = steps[index];
                                        steps[index] = steps[index - 1];
                                        steps[index - 1] = obj;
                                        setSteps([...steps]);
                                    }} type="primary" icon={<ArrowUpOutlined />} />}
                                </Space>
                            </Col>
                        </Row>
                    </Fragment>)
                }
                <Divider />
                <Row justify="end">
                    <Col>
                        <Button type="primary" onClick={() => addForm()} icon={<PlusOutlined />}></Button>
                    </Col>
                </Row>
            </>
        </Modal>
    </div>
}